<template>
  <div class="container-echart">
    <div :id="'echart' + timeId" class="interface-echart"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from "vue";
import * as echarts from "echarts";
import { EChartsType } from "echarts";

const timeId = ref(Math.floor(new Date().getTime() * Math.random())); // 使该图表保持唯id
let myEchart: EChartsType;
const X = ref(["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun1"]);
const Y = ref([150, 230, 224, 218, 135, 147, 2160]);
//--===============

const myEchartData = () => {
  const option = {
    xAxis: {
      type: "category",
      data: X.value,
    },
    yAxis: {
      type: "value",
    },
    series: [
      {
        data: Y.value,
        type: "line",
      },
    ],
  };
  // { notMerge: true } 解决删除数据时,数据不刷新的问题
  myEchart.setOption(option, { notMerge: true });
};

onMounted(() => {
  setTimeout(() => {
    const dom = document.getElementById(`echart${timeId.value}`) as any;
    myEchart = echarts.init(dom);
    myEchartData();
  }, 500);

  // 当窗口发生变化时
  window.addEventListener("resize", () => {
    myEchart.resize();
  });
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", () => {
    myEchart.resize();
  });
});
</script>

<style scoped>
.container-echart {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}
.interface-echart {
  width: 100%;
  height: 1000;
}
</style>